<?php
namespace app\index\controller;
use \think\Db;
use \think\Request;
use \Firebase\JWT\JWT;

class Base
{
    public $user = NULL;

    public function __construct(){
        header("Access-Control-Allow-Credentials:true");
        header("Access-Control-Allow-Origin:*");
        header("Access-Control-Max-Age:3600");
        header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,SessionToken");
        header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE');
        $info = $this->userinfo();
        if($info['code'] == -1) $this->error('no-login');
        if(Db::name("user")->where("id",$info['data']['id'])->value("delete_time")>0) $this->error("此账号已被封停");
    }
    protected function success($data,$msg='')
    {
        $data = ['code'=>1,'data'=>$data,'msg'=>$msg];
        header('Content-Type:application/json; charset=utf-8');
        echo json_encode($data);
        die();
    }

    protected function error($msg = '')
    {
        $data = ['code'=>-1,'msg'=>$msg ? $msg : 'error'];
        header('Content-Type:application/json; charset=utf-8');
        echo json_encode($data);
        die();
    }

    protected function getUserLevel($level){
        switch ($level){
            case 0:
                return '未开通会员';
            case 1:
                return 'V1 普通会员';
            case 2:
                return 'V2 黄金会员';
            case 3:
                return 'V3 白金会员';
            case 4:
                return 'V4 钻石会员';
            case 5:
                return 'V5 超级会员';
        }
        return '未知等级';
    }

    protected function verifyJwt($jwt)
    {
        $key = md5('fdsfe4gfgs');
        // JWT::$leeway = 3;
        try {
            $jwtAuth = json_encode(JWT::decode($jwt, $key, array('HS256')));
            $authInfo = json_decode($jwtAuth, true);
            if (!empty($authInfo['user_id'])) {
                return intval($authInfo['user_id']);
            } else {
                echo json_encode([
                    'code' => -1,
                    'msg' => 'Token验证不通过,用户不存在'
                ]);
            }
        } catch (\Firebase\JWT\SignatureInvalidException $e) {
            echo json_encode([
                'code' => -1,
                'msg' => 'Token无效'
            ]);
            exit;
        } catch (\Firebase\JWT\ExpiredException $e) {
            echo json_encode([
                'code' => -1,
                'msg' => 'Token过期'
            ]);
            exit;
        } catch (Exception $e) {
            echo json_encode([
                'code' => -1,
                'msg' => '系统错误，请稍候重试'
            ]);
            exit;
        }
    }

    public function userinfo(){
        $header = Request::instance()->header();
        if (!isset($header['token']) || $header['token'] == 'null') {
            return ['code'=>'-1',"msg"=>'no-login'];
        }else{
            $uid = $this->verifyJwt($header['token']);
            $user = Db::name("user")->alias("u")
                ->join("kl_member_info m","u.id=m.user_id","LEFT")
                ->where('u.id',$uid)
                ->where('u.user_type','member')->find();
            if(!$user) return ['code'=>'-1',"msg"=>'no-login'];
        }
        /*$userid = session('login_front_user_id');
        $user = Db::name("user")->alias("u")->join("kl_member_info m","u.id=m.user_id","LEFT")->where('u.id',$userid)->where('u.user_type','member')->find();
        if(!$user){
            session('login_front_user_id',null);
            return ['code'=>'-1',"msg"=>'no-login'];
        }*/
        $this->user = $user;
        $this->user['id'] = $user['user_id'];
        $data = ['id'=>$user['user_id'],'username'=>$user['username'],'usernick'=>$user['usernick'],'tuijianma'=>$user['tuijianma'],
            'money'=>$user['money'],'vip_level'=>$this->getUserLevel($user['vip_level']),'offers_days'=>$user['offers_days'],'free_times'=>$user['free_times'],
            'tuijian_count'=>$user['tuijian_count'],'end_time'=>$user['end_time'] ? ($user['end_time']>=time() ?  date('Y-m-d H:i:s',$user['end_time']) :'已到期') : '','
                last_login_time'=>$user['last_login_time'] ? date('Y-m-d H:i:s',$user['last_login_time']) : ''];
        $data['server_qq'] = Db::name("user")->where("id",$user['parent_id'])->value("qq");
        if(strlen($data['server_qq']) == 0) $data['server_qq'] = Db::name("user")->where("user_type",'admin')->value("qq");

        return ['code'=>1,'data'=>$data,'msg'=>'用户已登陆'];
    }

    protected function get_client_ip($type = 0) {
        $type       =  $type ? 1 : 0;
        static $ip  =   NULL;
        if ($ip !== NULL) return $ip[$type];
        if(isset($_SERVER['HTTP_X_REAL_IP'])){//nginx 代理模式下，获取客户端真实IP
            $ip=$_SERVER['HTTP_X_REAL_IP'];
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {//客户端的ip
            $ip     =   $_SERVER['HTTP_CLIENT_IP'];
        }elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {//浏览当前页面的用户计算机的网关
            $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos    =   array_search('unknown',$arr);
            if(false !== $pos) unset($arr[$pos]);
            $ip     =   trim($arr[0]);
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];//浏览当前页面的用户计算机的ip地址
        }else{
            $ip=$_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u",ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }
}
